package com.travel.interceptor;

/**
 * @author: libin
 * Date: 2025/6/18 16:20
 * Description:
 **/
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ObjectUtil;
import com.travel.context.UserContext;
import com.travel.service.impl.TokenService;
import com.travel.utils.StringUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author: libin
 * Date: 2025/6/10 8:18
 * Description: 会员登录拦截器，认证失败时返回401状态码
 **/
@Component
@Slf4j
public class MemberLoginInterceptor1 implements HandlerInterceptor {

    @Autowired
    private TokenService tokenService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("请求被拦截: {}", request.getRequestURL().toString());

        // 如果不是映射到方法，直接通过
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }

        // 跨域预检请求（OPTIONS方法）直接放行
        if ("OPTIONS".equals(request.getMethod())) {
            return true;
        }

        // 获取token
        String token = request.getHeader("authorization");
        if (StringUtils.isEmpty(token)) {
            sendUnauthorizedResponse(response, "认证失败：Token为空");
            return false;
        }

        // 解析token
        Claims claims;
        try {
            claims = tokenService.parseToken(token);
        } catch (Exception e) {
            log.error("Token解析失败", e);
            sendUnauthorizedResponse(response, "认证失败：Token解析错误");
            return false;
        }

        if (ObjectUtil.isEmpty(claims)) {
            sendUnauthorizedResponse(response, "认证失败：Token无效");
            return false;
        }

        // 获取token中的用户ID
        Integer userId = MapUtil.get(claims, "userId", Integer.class);
        if (ObjectUtils.isEmpty(userId)) {
            sendUnauthorizedResponse(response, "认证失败：用户ID缺失");
            return false;
        }

        // 存储到ThreadLocal中
        UserContext.setCurrentId(userId);
        return true;
    }

    /**
     * 发送401未授权响应
     */
    private void sendUnauthorizedResponse(HttpServletResponse response, String message) throws IOException {
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); // 设置401状态码
        response.setContentType("application/json;charset=UTF-8");

        // 构建错误响应体（可根据需求调整格式）
        String errorResponse = "{\"code\": 401, \"message\": \"" + message + "\"}";

        PrintWriter writer = response.getWriter();
        writer.write(errorResponse);
        writer.flush();
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 清理ThreadLocal中存储的数据
        UserContext.removeCurrentId();
    }
}
